#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

import datetime, time, requests
import json
from django_redis import get_redis_connection

from activities.models import Channel
from equity_mall.utils.synchronization_kl_order import get_result, get_ylx_logincode, staff_qrcode_status, pull_StaffQrcodeLogin
from equity_admin.utils import get_alidiscountcoupon


def update_gzh_accesstoken():
    url = 'http://api.wpost.cn/wxapi/accesstoken'
    response = requests.get(url)
    data = response.json()
    redis_conn = get_redis_connection("gzh_accesstoken")
    redis_conn.set("gzh_accesstoken", data['accesstoken'])
    return data['accesstoken']


def refresh_effective_cookie():
    print('%s: refresh_effective_cookie' % time.ctime())
    redis_conn1 = get_redis_connection("gzh_accesstoken")
    gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
    if not gzh_accesstoken:
        access_token = update_gzh_accesstoken()
    else:
        access_token = gzh_accesstoken.decode()
    headers1 = {"Content-Type": "application/json"}
    ali_cookies = Channel.objects.get(id=1)
    headers = {
        'Cookie': ali_cookies.cookie,
        'referer': 'https://p.alipay.com/workspace/account'
    }
    url = 'https://p.alipay.com/isv/queryAccountBaseInfo.json'
    response = requests.get(url, headers=headers)
    try:
        data = response.json()
        print(data)
    except:
        print(f'阿里刷新失败')
    url = 'https://market.alipay.com/activity/queryActivityLiteInfo.json?activityId=2021071600826004355213787710'
    headers['referer'] = 'https://market.alipay.com/activity/queryActivityLiteInfo.json'
    response = requests.get(url, headers=headers)
    try:
        data = response.json()
        print(data)
        if 'stat' in data:
            data = {
                "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
                "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
                "url": 'https://api.sutpay.com/admin/hand_movement/?id=1',
                "data": {
                    "first": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword1": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword2": {
                        "value": '远程服务器出问题',
                        "color": "#878787"
                    },
                    "remark": {
                        "value": '请人工刷新token,并检查远程服务器!',
                        "color": "#878787"
                    }
                }
            }
            response = requests.post(
                url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                data=json.dumps(data), headers=headers1)
            if response.json()['errcode'] != 0:
                access_token = update_gzh_accesstoken()
                response = requests.post(
                    url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                    data=json.dumps(data), headers=headers1)
    except Exception as e:
        print(e)
        print(f'阿里刷新失败')
    print('结束')
    return '结束'


def refresh_effective_cookie1():
    print('%s: refresh_effective_cookie1' % time.ctime())
    redis_conn1 = get_redis_connection("gzh_accesstoken")
    gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
    if not gzh_accesstoken:
        access_token = update_gzh_accesstoken()
    else:
        access_token = gzh_accesstoken.decode()
    headers1 = {"Content-Type": "application/json"}
    ali_cookies = Channel.objects.get(id=8)
    headers = {
        'Cookie': ali_cookies.cookie,
        'referer': 'https://p.alipay.com/workspace/account'
    }
    url = 'https://p.alipay.com/isv/queryAccountBaseInfo.json'
    response = requests.get(url, headers=headers)
    try:
        data = response.json()
        print(data)
    except:
        print(f'阿里刷新失败')
    try:
        url = 'https://open.alipay.com/platform/changeIdentity.json'
        body = {"appId": "2021004128623106"}
        headers['Referer'] = 'https://open.alipay.com/develop/pm/sub/appinfo?appId=2021004128623106'
        data = requests.post(url=url, data=body, headers=headers).json()
        print(data)
        # url = 'https://spcenter.alipay.com/pamir/login/queryLoginAccount.json'
        # data = requests.get(url=url, headers=headers).json()
        # print(data)
        if data['stat'] != 'ok':
            data = {
                "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
                "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
                "url": 'https://api.sutpay.com/admin/hand_movement/?id=3',
                "data": {
                    "first": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword1": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword2": {
                        "value": '远程服务器出问题',
                        "color": "#878787"
                    },
                    "remark": {
                        "value": '请人工刷新token,并检查远程服务器!',
                        "color": "#878787"
                    }
                }
            }
            response = requests.post(
                url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                data=json.dumps(data), headers=headers1)
            if response.json()['errcode'] != 0:
                access_token = update_gzh_accesstoken()
                response = requests.post(
                    url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                    data=json.dumps(data), headers=headers1)
    except Exception as e:
        print(e)
        print(f'阿里刷新失败')
    print('结束')
    return '结束'


def refresh_effective_cookie2():
    print('%s: refresh_effective_cookie' % time.ctime())
    redis_conn1 = get_redis_connection("gzh_accesstoken")
    gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
    if not gzh_accesstoken:
        access_token = update_gzh_accesstoken()
    else:
        access_token = gzh_accesstoken.decode()
    headers1 = {"Content-Type": "application/json"}
    ali_cookies = Channel.objects.get(id=14)
    headers = {
        'Cookie': ali_cookies.cookie,
        'referer': 'https://p.alipay.com/workspace/account'
    }
    url = 'https://p.alipay.com/isv/queryAccountBaseInfo.json'
    response = requests.get(url, headers=headers)
    try:
        data = response.json()
        print(data)
    except:
        print(f'阿里刷新失败')
    url = 'https://market.alipay.com/activity/queryActivityLiteInfo.json?activityId=2020071400826004230107764795'
    headers['referer'] = 'https://market.alipay.com/activity/queryActivityLiteInfo.json'
    response = requests.get(url, headers=headers)
    try:
        data = response.json()
        print(data)
        if 'stat' in data:
            data = {
                "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
                "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
                "url": 'https://api.sutpay.com/admin/hand_movement/?id=2',
                "data": {
                    "first": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword1": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword2": {
                        "value": '远程服务器出问题',
                        "color": "#878787"
                    },
                    "remark": {
                        "value": '请人工刷新token,并检查远程服务器!',
                        "color": "#878787"
                    }
                }
            }
            response = requests.post(
                url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                data=json.dumps(data), headers=headers1)
            print(response.json())
            if response.json()['errcode'] != 0:
                access_token = update_gzh_accesstoken()
                response = requests.post(
                    url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                    data=json.dumps(data), headers=headers1)
    except:
        print(f'阿里刷新失败')
    url = 'https://devicedata.alipay.com/devicedata/open/downloadTask/deviceDownloadTask'
    headers['referer'] = 'https://b.alipay.com/'
    response = requests.get(url, headers=headers)
    try:
        data = response.json()
        print(data)
        if 'stat' in data:
            data = {
                "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
                "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
                "url": 'https://api.sutpay.com/admin/hand_movement/?id=2',
                "data": {
                    "first": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword1": {
                        "value": '阿里认证已失效!',
                        "color": "#878787"
                    },
                    "keyword2": {
                        "value": '远程服务器出问题',
                        "color": "#878787"
                    },
                    "remark": {
                        "value": '请人工刷新token,并检查远程服务器!',
                        "color": "#878787"
                    }
                }
            }
            response = requests.post(
                url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                data=json.dumps(data), headers=headers1)
            print(response.json())
            if response.json()['errcode'] != 0:
                access_token = update_gzh_accesstoken()
                response = requests.post(
                    url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                    data=json.dumps(data), headers=headers1)
    except:
        print(f'阿里刷新失败')
    print('结束')
    return '结束'


def refresh_effective_wxcookie():
    print('%s: refresh_effective_wxcookie' % time.ctime())
    redis_conn1 = get_redis_connection("gzh_accesstoken")
    gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
    if not gzh_accesstoken:
        access_token = update_gzh_accesstoken()
    else:
        access_token = gzh_accesstoken.decode()
    headers1 = {"Content-Type": "application/json"}
    cookies = Channel.objects.filter(id__in=[4])
    for cookie in cookies:
        headers = {'Cookie': cookie.cookie}
        url = 'https://pay.weixin.qq.com/index.php/core/risk_ctrl/query_sec_factor_status'
        response = requests.get(url, headers=headers)
        try:
            data = response.json()
            data['mchid'] = cookie.mchid
            cookies_dict = {}
            cookies_list = cookie.cookie.replace(' ', '').split(';')
            for cookies_str in cookies_list:
                if cookies_str:
                    cookies_str = cookies_str.split('=')
                    cookies_dict[cookies_str[0]] = cookies_str[1]
            if cookie.mchid != cookies_dict['merchant_code']:
                data = {
                    "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
                    "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
                    "url": f'https://api.sutpay.com/admin/wxpay_cookie/?id={cookie.id}',
                    "data": {
                        "first": {
                            "value": f'{cookie.mchid}认证已失效!',
                            "color": "#878787"
                        },
                        "keyword1": {
                            "value": f'{cookie.mchid}认证已失效,更新错误平台',
                            "color": "#878787"
                        },
                        "keyword2": {
                            "value": f'当前有效cookie{cookies_dict["merchant_id"]}',
                            "color": "#878787"
                        },
                        "remark": {
                            "value": '请人工刷新token,并检查远程服务器!',
                            "color": "#878787"
                        }
                    }
                }
                response = requests.post(
                    url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                    data=json.dumps(data), headers=headers1)
            print(data)
        except:
            data = {
                "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
                "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
                "url": f'https://api.sutpay.com/admin/wxpay_cookie/?id={cookie.id}',
                "data": {
                    "first": {
                        "value": f'{cookie.mchid}认证已失效!',
                        "color": "#878787"
                    },
                    "keyword1": {
                        "value": f'{cookie.mchid}认证已失效',
                        "color": "#878787"
                    },
                    "keyword2": {
                        "value": '远程服务器出问题',
                        "color": "#878787"
                    },
                    "remark": {
                        "value": '请人工刷新token,并检查远程服务器!',
                        "color": "#878787"
                    }
                }
            }
            response = requests.post(
                url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                data=json.dumps(data), headers=headers1)
            print(response.json())
            if response.json()['errcode'] != 0:
                access_token = update_gzh_accesstoken()
                requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}', data=json.dumps(data), headers=headers1)
            print(f'{cookie.mchid}刷新失败')
    print('结束')
    return '结束'


def check_ylx_identity():
    print('%s: check_ylx_identity' % time.ctime())
    method = 'ExportList'
    body = {"page": "1", "status": "RUNNING"}
    result = json.loads(get_result(method, body))
    if result['meta']['code'] != 200:
        cookie = Channel.objects.get(id=5)
        redis_conn1 = get_redis_connection("gzh_accesstoken")
        gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
        if not gzh_accesstoken:
            access_token = update_gzh_accesstoken()
        else:
            access_token = gzh_accesstoken.decode()
        headers = {"Content-Type": "application/json"}
        qrcode = get_ylx_logincode()
        no = qrcode['data']['no']
        data = {
            "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
            "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
            "url": qrcode['data']['url'],
            "data": {
                "first": {
                    "value": f'【邮乐享】认证已失效!',
                    "color": "#878787"
                },
                "keyword1": {
                    "value": '【邮乐享】认证已失效!',
                    "color": "#878787"
                },
                "keyword2": {
                    "value": f'当前有效cookie',
                    "color": "#878787"
                },
                "remark": {
                    "value": '请人工刷新token,并检查远程服务器!',
                    "color": "#878787"
                }
            }
        }
        response = requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}', data=json.dumps(data), headers=headers)
        print(response.json())
        if response.json()['errcode'] != 0:
            access_token = update_gzh_accesstoken()
            requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}', data=json.dumps(data), headers=headers)
        a = 1
        while True:
            result = staff_qrcode_status(no)
            print(result)
            if result['data']['adminData']['loginStatus']:
                cookie.cookie = f'{result["data"]["manageToken"]["jwtConfig"]["headerPrefix"]} {result["data"]["manageToken"]["tokenData"]["token"]}'
                cookie.ecc_csrf_token = result['data']['adminData']['userID']
                cookie.save()
                break
            if a == 6:
                break
            time.sleep(10)
            a += 1
    return result


def login_ylx_identity():
    print('%s: check_ylx_identity' % time.ctime())
    cookie = Channel.objects.get(id=5)
    qrcode = get_ylx_logincode()
    no = qrcode['data']['no']
    pull_StaffQrcodeLogin(no)
    a = 1
    while True:
        result = staff_qrcode_status(no)
        print(result)
        if result['data']['adminData']['loginStatus']:
            cookie.cookie = f'{result["data"]["manageToken"]["jwtConfig"]["headerPrefix"]} {result["data"]["manageToken"]["tokenData"]["token"]}'
            cookie.ecc_csrf_token = result['data']['adminData']['userID']
            cookie.save()
            break
        if a == 6:
            break
        time.sleep(10)
        a += 1
    return result


def update_wyf_accesstoken():
    print('%s: update_wyf_accesstoken' % time.ctime())
    cookie_set = Channel.objects.filter(channel_type=4)
    for cookie in cookie_set:
        appid = cookie.mchid
        secret = cookie.api_key
        url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}'
        response = requests.get(url=url)
        result = response.json()
        print(result)
        access_token = result['access_token']
        expires_in = result['expires_in']
        cookie.token = access_token
        cookie.ecc_csrf_token = int(time.time())
        cookie.save()
    return '更新成功'


def push_uncluster_failure(order_id):
    '''推送解团失败'''
    redis_conn1 = get_redis_connection("gzh_accesstoken")
    gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
    if not gzh_accesstoken:
        access_token = update_gzh_accesstoken()
    else:
        access_token = gzh_accesstoken.decode()
    headers = {"Content-Type": "application/json"}
    data = {
        "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
        "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
        "url": 'https://api.sutpay.com/admin/hand_movement/?id=1',
        "data": {
            "first": {
                "value": '拼团取消失败!',
                "color": "#878787"
            },
            "keyword1": {
                "value": '拼团取消失败!',
                "color": "#878787"
            },
            "keyword2": {
                "value": f'订单号{order_id}',
                "color": "#878787"
            },
            "remark": {
                "value": '拼团取消失败!',
                "color": "#878787"
            }
        }
    }
    response = requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}', data=json.dumps(data), headers=headers)
    if response.json()['errcode'] != 0:
        access_token = update_gzh_accesstoken()
        response = requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}', data=json.dumps(data), headers=headers)


if __name__ == '__main__':
    login_ylx_identity()